﻿using Microsoft.AspNetCore.Mvc;
using WoodAdmin.Common.Attribute;
using WoodAdmin.Common.Helper;
using WoodAdmin.Common.Helper.Log;
using WoodAdmin.Models;
using WoodAdmin.Models.ViewModels;
using WoodAdmin.Services;
using System;
using System.Text;

namespace WoodAdmin.Controllers
{
    public class LoginController : BaseController
    {
        private readonly LoginService _loginService;

        public LoginController(LoginService loginService)
        {
            _loginService = loginService;
        }

        #region 登录
        [HttpGet]
        [SkipCheckLogin]
        [SkipCheckPermission]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [SkipCheckLogin]
        [SkipCheckPermission]
        public IActionResult Login(LoginViewModel model)
        {
            #region 验证信息
            if (model?.VerifyCode!=CacheHelper.CacheValue(APPKeys.Vercode)?.ToString())
            {
                return JsonError("验证码错误！");
            }
            //RSA解密前台传入的密码
            var rsa = new RSAHelper(RSAType.RSA, Encoding.UTF8, APPKeys.PrivateKey, APPKeys.PublicKey);
            model.Password = rsa.Decrypt(model.Password);
            #endregion

            //如果用户存在
            if (_loginService.IsUserExist(model))
            {
                var user = _loginService.GetUserByUserNameAndPass(model);
                GlobalHelper.SetCurrentUserInfo(user);

                #region 记录登录日志
                LoginLogHandler loginLog = new LoginLogHandler();
                loginLog.WriteLog();
                #endregion

                return JsonSuccess("登录成功！");
            }
            return JsonError("用户名或密码不正确！");
        }
        #endregion

        #region 验证码
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [SkipCheckLogin]
        [SkipCheckPermission]
        public IActionResult VerifyCode()
        {
            var imgBytes = _loginService.GetVcode();
            return File(imgBytes, @"image/jpeg");
        }
        #endregion
    }
}